package com.mhtool.core.collection;

import lombok.experimental.UtilityClass;
import org.apache.commons.collections4.CollectionUtils;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author yin
 * @date 2021/12/27 17:20
 * @since 8.0.0
 */
@UtilityClass
public class ArrayUtils extends org.apache.commons.lang3.ArrayUtils {
    public static String[] toArray(List<String> list) {
        if (CollectionUtils.isEmpty(list)) {
            return new String[0];
        }
        return list.toArray(new String[]{});
    }

    public static List<Byte> asList(byte[] src) {
        if (isEmpty(src)) {
            return Collections.emptyList();
        }
        List<Byte> r = new ArrayList<>(src.length);
        for (byte l : src) {
            r.add(l);
        }
        return r;
    }
    public static List<Integer> asList(int[] src) {
        if (isEmpty(src)) {
            return Collections.emptyList();
        }
        List<Integer> r = new ArrayList<>(src.length);
        for (int l : src) {
            r.add(l);
        }
        return r;
    }
    public static List<Long> asList(long[] src) {
        if (isEmpty(src)) {
            return Collections.emptyList();
        }
        List<Long> r = new ArrayList<>(src.length);
        for (long l : src) {
            r.add(l);
        }
        return r;
    }
    public static byte[] toPrimitiveByte(List<Byte> list) {
        if (CollectionUtils.isEmpty(list)) {
            return org.apache.commons.lang3.ArrayUtils.EMPTY_BYTE_ARRAY;
        }
        byte[] result = new byte[list.size()];
        for (int i = list.size() - 1; i >= 0; i--) {
            result[i] = list.get(i);
        }
        return result;
    }
    public static int[] toPrimitiveInt(List<Integer> list) {
        if (CollectionUtils.isEmpty(list)) {
            return EMPTY_INT_ARRAY;
        }
        int[] result = new int[list.size()];
        for (int i = list.size() - 1; i >= 0; i--) {
            result[i] = list.get(i);
        }
        return result;
    }
    public static long[] toPrimitiveLong(List<Long> list) {
        if (CollectionUtils.isEmpty(list)) {
            return EMPTY_LONG_ARRAY;
        }
        long[] result = new long[list.size()];
        for (int i = list.size() - 1; i >= 0; i--) {
            result[i] = list.get(i);
        }
        return result;
    }

    /**
     * 新建一个空数组
     *
     * @param <T>           数组元素类型
     * @param componentType 元素类型
     * @param newSize       大小
     * @return 空数组
     */
    @SuppressWarnings("unchecked")
    public static <T> T[] newArray(Class<?> componentType, int newSize) {
        return (T[]) Array.newInstance(componentType, newSize);
    }
}